﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
using ICSharpCode.SharpZipLib.Zip;
namespace QDP.Platform.Loader
{
    public class ZipThemeParser : IParser
    {
        public void Parse(string file,Stream stream)
        {
            Dictionary<string, string> xamls = new Dictionary<string, string>();
            using (ZipInputStream s = new ZipInputStream(stream))
            {
                ZipEntry theEntry;
                try
                {
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        byte[] bs = new byte[theEntry.Size];
                        s.Read(bs, 0, bs.Length);
                        StreamReader r = new StreamReader(new MemoryStream(bs));
                        xamls.Add(theEntry.Name, r.ReadToEnd());
                    }
                    var xamldata = (from xaml in xamls
                                    orderby xaml.Key
                                    select xaml);
                    foreach (var xaml in xamldata)
                    {
                        try
                        {
                            object xamlObj = XamlReader.Load(xaml.Value);
                            if (xamlObj is ResourceDictionary)
                            {
                                Application.Current.Resources.MergedDictionaries.Add(xamlObj as ResourceDictionary);
                            }
                        }
                        catch (XamlParseException xpex)
                        {
                            D.Debug("err:" + xpex.Message + " file:" + file +"  child:"+xaml.Key);
#if DEBUG
                            MessageBox.Show(file + "\r\n" + xpex.Message);
#endif
                        }
                    }
                }
                catch (Exception ex)
                {
                    D.Debug("err:" + ex.Message + " file:" + file);
#if DEBUG
                    MessageBox.Show(file + "\r\n" + ex.Message);
#endif
                }
            }
        }
    }
}